package com.itheima.admin.task;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.itheima.admin.service.WemediaNewsAutoScanService;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.util.RequestContextUtil;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.dto.WmNewsPageReqDto;
import com.itheima.wemedia.feign.WmNewsFeign;
import com.itheima.wemedia.vo.WmNewsVo;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class SyncArticleTask {
    @Autowired
    private WmNewsFeign wmNewsFeign;

    @Autowired
    private WemediaNewsAutoScanService wemediaNewsAutoScanService;

    @XxlJob("syncArticleTask")
    public ReturnT<String> syncArticleJob(String param){
        log.info("开始执行同步文章任务：param={}",param);

        //远程调用查询文章 处理
        WmNewsPageReqDto dto = new WmNewsPageReqDto();
        //查询数据库中是否有状态为4，或者8的文章

        //状态为8、4--人工审核通过的也需要同步
        dto.setEndPubDate(new Date());
        syncArticle(param, dto);
        return ReturnT.SUCCESS;
    }

    private void syncArticle(String param, WmNewsPageReqDto dto) {
        //远程调用文章微服务
        ResultVo<List<WmNewsVo>> listResultVo = wmNewsFeign.listArticleSync(dto);
        //判断结果
        if(listResultVo.isSuccess()){
            List<WmNewsVo> list = listResultVo.getData();
            log.info("同步文章任务完成：param={},listSize={}",param,list.size());
            XxlJobLogger.log("同步文章任务：listSize={}",list.size());

            if(CollectionUtils.isNotEmpty(list)){
                list.forEach(wmNewsVo -> {
                    boolean flag = wemediaNewsAutoScanService.syncArticleInfo(wmNewsVo);
                    if(flag){
                        log.info("同步文章数据成功：wmNewsId={}", wmNewsVo.getId());
                        XxlJobLogger.log("同步文章数据成功：wmNewsId={}", wmNewsVo.getId());
                    }else{
                        log.info("同步文章数据失败：wmNewsId={}", wmNewsVo.getId());
                        XxlJobLogger.log("同步文章数据失败：wmNewsId={}", wmNewsVo.getId());
                    }
                });
            }
        }
    }
}
